<template>
  <div class="app-container">
    <sticky class="filter-container">
      <el-row :gutter="20">
        <el-col :span="16">
          <el-input
            v-model="listSearch.search"
            placeholder="搜索"
            style="margin-right: 10px;width: 200px"
            class="filter-item"
            size="mini"
            clearable
            @keyup.enter.native="handleSearch"
            @clear="handleSearch"
            @blur="handleSearch"
          />
          <el-button
            v-waves
            class="filter-item"
            size="mini"
            type="primary"
            icon="el-icon-search"
            @click="handleSearch"
          >
            搜索
          </el-button>
          <el-button
            v-waves
            class="filter-item"
            size="mini"
            type="primary"
            icon="el-icon-refresh-right"
            :loading="refreshLoading"
            @click="refresh"
          />
        </el-col>
        <el-col :span="8" style="text-align: right">
          <el-dropdown v-if="checkPermission(['admin', 'role_all', 'role_export'])" trigger="click">
            <el-button
              v-waves
              :loading="downLoading"
              class="filter-item"
              size="mini"
              type="primary"
              icon="el-icon-download"
              style="margin-right: 10px;"
            >
              导出
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="handleDownloadCurrent">导出当前</el-dropdown-item>
              <el-dropdown-item @click.native="handleDownloadAll">导出所有</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button
            v-if="checkPermission(['admin','role_all','role_create'])"
            v-waves
            class="filter-item"
            size="mini"
            type="primary"
            icon="el-icon-plus"
            @click="showAdd"
          >
            新增
          </el-button>
        </el-col>
      </el-row>
    </sticky>
    <el-row :gutter="28">
      <el-col :span="span">
        <!--表格渲染-->
        <el-table
          :data="list"
          style="width: 100%"
          highlight-current-row
          @current-change="headerCurrentChange"
        >
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-form label-position="left" inline class="demo-table-expand">
                <el-form-item label="角色名">
                  <span>{{ scope.row.name }}</span>
                </el-form-item>
                <el-form-item v-show="scope.row.id !== 1" label="父级菜单">
                  <span>{{ scope.row.department }}</span>
                </el-form-item>
                <el-form-item label="描述">
                  <span>{{ scope.row.desc }}</span>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column
            label="角色名"
            prop="name"
          />
          <el-table-column
            label="描述"
            prop="desc"
          />
          <el-table-column
            label="操作"
            width="100%"
          >
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" content="编辑" placement="top">
                <el-button
                  v-if="checkPermission(['admin','role_all','role_edit'])"
                  :disabled="scope.row.id === 1"
                  type="text"
                  icon="el-icon-edit"
                  @click="showEdit(scope.row.id)"
                />
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="删除" placement="top">
                <el-button
                  v-if="checkPermission(['admin','role_all','role_delete'])"
                  :disabled="scope.row.id === 1"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                />
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-pagination
          style="text-align: right; margin-top: 20px"
          background
          :hide-on-single-page="true"
          :current-page="listSearch.page"
          :page-size="listSearch.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="listSearch.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-col>
      <el-col :span="7">
        <el-card v-if="show && checkPermission(['admin','role_all','role_edit'])" class="box-card">
          <div slot="header" class="clearfix">
            <span><el-tag type="primary">菜单分配</el-tag>  <el-tag type="primary">{{ rowData.name }}</el-tag></span>
            <el-button
              v-if="checkPermission(['admin','role_all','role_edit'])"
              v-waves
              :loading="loading"
              class="filter-item"
              size="mini"
              type="primary"
              style="float: right"
              @click="saveMenu"
            >
              保存
            </el-button>
          </div>
          <el-tree
            ref="menu"
            :data="menuList"
            show-checkbox
            check-strictly
            accordion
            node-key="id"
            :default-expanded-keys="menuIds"
            :default-checked-keys="menuIds"
            :props="defaultProps"
            highlight-current
          />
        </el-card>
      </el-col>
      <el-col :span="7">
        <el-card v-if="show && checkPermission(['admin','role_all','role_edit'])" class="box-card">
          <div slot="header" class="clearfix">
            <span><el-tag type="primary">权限分配</el-tag>  <el-tag type="primary">{{ rowData.name }}</el-tag></span>
            <el-button
              v-if="checkPermission(['admin','role_all','role_edit'])"
              v-waves
              :loading="loading"
              class="filter-item"
              size="mini"
              type="primary"
              style="float: right"
              @click="savePermission()"
            >
              保存
            </el-button>
          </div>
          <el-tree
            ref="permission"
            :data="permissionList"
            show-checkbox
            check-strictly
            accordion
            node-key="id"
            :default-expanded-keys="permissionIds"
            :default-checked-keys="permissionIds"
            :props="defaultProps"
            highlight-current
          />
        </el-card>
      </el-col>
    </el-row>
    <!-- 弹框组件 -->
    <vForm :vdialog="dialog" :vtitle="title" :visedit="isedit" :vformid="formid" @changeShow="showUpdate" />
  </div>
</template>

<script>
import Sticky from '@/components/Sticky/index'
import waves from '@/directive/waves/waves'
import vForm from '@/views/system/role/components/form'
import { listRole, delRole, saveMenu, savePermission, exportRoleCurrent, exportRoleAll } from '@/api/role'
import { treeMenu } from '@/api/menu'
import { treePermission } from '@/api/permission'
import checkPermission from '@/utils/permission'

export default {
  components: { Sticky, vForm },
  directives: { waves },
  data() {
    return {
      url_api: process.env.VUE_APP_BASE_API,
      refreshLoading: false,
      downLoading: false,
      loading: false,
      is_permissions: false,
      rowData: null,
      menuList: [],
      menuIds: [],
      permissionList: [],
      permissionIds: [],
      show: false,
      defaultProps: {
        children: 'children',
        label: 'label'
      },

      span: 24,
      listLoading: false,
      list: [],
      listSearch: {
        total: 0,
        page: 1,
        pageSize: 10,
        search: ''
      },
      // 弹出框定义属性
      // （与子组件的 props 属性一致）dialog 控制新增、编辑、查看弹窗的显示与隐藏
      dialog: false,
      title: '',
      isedit: '',
      formid: 0
      // 弹出框定义属性
    }
  },
  created() {
    this.getTreeMenu()
    this.getTreePermission()
  },
  mounted() {
    this.getList()
  },
  methods: {
    // checkPermission 权限检查
    checkPermission,
    // 弹出框
    // 点击按钮事件，显示弹窗组件
    showAdd() {
      this.dialog = true
      this.title = '新增角色'
      this.isedit = 'add'
      this.span = 24
      this.show = false
    },
    showEdit(row) {
      this.dialog = true
      this.title = '编辑角色'
      this.isedit = 'edit'
      this.formid = row
    },
    // 监听 子组件弹窗关闭后触发，由子组件调用
    showUpdate(val, valid, vname) {
      if (val === 'false') {
        this.dialog = false
        this.formid = valid
        if (vname) {
          this.rowData.id = valid
          this.rowData.name = vname
        }
      } else {
        this.dialog = true
      }
    },
    // 弹出框
    // 列表
    getList() {
      this.listLoading = true
      listRole(this.listSearch).then(res => {
        this.list = res.data
        this.listSearch.total = res.count
        this.listLoading = false
      })
    },
    // 列表
    // 搜索
    handleSearch() {
      // 当页面不在第一页时搜索内容报错
      this.listSearch.page = 1
      this.getList()
    },
    // 搜索
    // 分页
    handleSizeChange(val) {
      this.listSearch.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listSearch.page = val
      this.getList()
    },
    // 分页
    // 表格触发事件
    headerCurrentChange(val) {
      if (val) {
        if (val.id !== 1) {
          if (this.show) {
            // 清空选中状态
            this.$refs.permission.setCheckedKeys([])
            this.$refs.menu.setCheckedKeys([])
          }
          this.span = 10
          this.show = true
          this.rowData = val
          if (this.rowData) {
            this.permissionIds = this.rowData.permissions
            this.menuIds = this.rowData.menus
          }
        } else {
          this.$notify.warning({
            type: 'warning',
            title: '提示',
            message: '系统默认管理员不可修改',
            showClose: true,
            duration: 5 * 1000
          })
        }
      }
    },
    // 表格触发事件
    // 删除
    handleDelete(row) {
      this.$confirm('此操作不能撤销，所属该角色的用户均失去相应权限, 是否继续删除【 ' + row.name + ' 】角色', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.listLoading = true
        delRole(row.id).then((res) => {
          this.listLoading = false
          this.$notify.success({
            type: 'success',
            title: '成功',
            message: '【 ' + row.name + ' 】已删除',
            showClose: true,
            duration: 5 * 1000
          })
          this.span = 24
          this.show = false
          if (this.listSearch.total % 10 === 1) {
            if (this.listSearch.page !== 1) {
              this.listSearch.page = this.listSearch.page - 1
            }
          }
          this.getList()
        })
      }).catch(() => {
        this.$notify.info({
          type: 'info',
          title: '提示',
          message: '已取消删除',
          showClose: true,
          duration: 5 * 1000
        })
      })
    },
    // 删除
    // 导出
    handleDownloadCurrent() {
      this.downLoading = true
      exportRoleCurrent(this.listSearch).then(res => {
        const url = this.url_api + 'media/export/' + res.data.name
        window.open(url)
        this.downLoading = false
        this.$notify.success({
          type: 'success',
          title: '成功',
          message: res.data.name + res.message,
          showClose: true,
          duration: 5 * 1000
        })
      })
    },
    handleDownloadAll() {
      this.downLoading = true
      exportRoleAll().then(res => {
        const url = this.url_api + 'media/export/' + res.data.name
        window.open(url)
        this.downLoading = false
        this.$notify.success({
          type: 'success',
          title: '成功',
          message: res.data.name + res.message,
          showClose: true,
          duration: 5 * 1000
        })
      })
    },
    // 导出
    // 目录树
    getTreeMenu() {
      treeMenu().then(res => {
        this.menuList = res.data
      })
    },
    getTreePermission() {
      treePermission().then(res => {
        this.permissionList = res.data
      })
    },
    // 目录树
    // 保存菜单/权限
    saveMenu() {
      this.loading = true
      const form = { menus: this.$refs.menu.getCheckedKeys() }
      saveMenu(this.rowData.id, form).then(res => {
        this.rowData.menus = res.data.menus
        this.$notify.success({
          type: 'success',
          title: '提示',
          message: '菜单保存',
          showClose: true,
          duration: 5 * 1000
        })
      })
      this.loading = false
    },
    savePermission() {
      this.loading = true
      const form = { permissions: this.$refs.permission.getCheckedKeys() }
      savePermission(this.rowData.id, form).then(res => {
        this.rowData.permissions = res.data.permissions
        this.$notify.success({
          type: 'success',
          title: '提示',
          message: '权限保存',
          showClose: true,
          duration: 5 * 1000
        })
      })
      this.loading = false
    },
    // 保存菜单/权限
    // 刷新
    refresh() {
      this.refreshLoading = true
      this.getList()
      this.show = false
      this.span = 24
      this.refreshLoading = false
      this.$notify.info({
        type: 'info',
        title: '提示',
        message: '已刷新',
        showClose: true,
        duration: 5 * 1000
      })
    }
    // 刷新
  }
}
</script>

<style scoped>
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>
